package indi.yangshenhui.tool;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtil {

	private RegexUtil() {
	}

	public static boolean matcher(String regex, String content) {
		Matcher matcher = Pattern.compile(regex).matcher(content);
		return matcher.matches();
	}

	/**
	 * 获得匹配的字符串
	 * 
	 * @param regex
	 *            匹配的正则
	 * @param content
	 *            被匹配的内容
	 * @param groupIndex
	 *            匹配正则的分组序号
	 * @return 匹配后得到的字符串,未匹配返回null
	 */
	public static String get(String regex, String content, int groupIndex) {
		Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(
				content);
		if (matcher.find()) {
			return matcher.group(groupIndex);
		}
		return null;
	}

	/**
	 * 取得内容中匹配的所有结果
	 * 
	 * @param regex
	 *            正则
	 * @param content
	 *            被查找的内容
	 * @param group
	 *            正则的分组
	 * @param collection
	 *            返回的集合类型
	 * @return 结果集
	 */
	public static <T extends Collection<String>> T findAll(String regex,
			String content, int group, T collection) {
		Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(
				content);
		while (matcher.find()) {
			collection.add(matcher.group(group));
		}
		return collection;
	}

	/**
	 * 判断该字符串是否是IPV4地址
	 * 
	 * @param ip
	 *            IP地址
	 * @return 是否是IPV4
	 */
	public static boolean isIpv4(String ip) {
		if (StringUtil.isEmpty(ip)) {
			return false;
		}
		String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
		return Pattern.matches(regex, ip);
	}

}